package com.bedrock.project.inside.api.v1;

import com.bedrock.common.constant.UserConstants;
import com.bedrock.framework.aspectj.lang.annotation.Log;
import com.bedrock.framework.aspectj.lang.enums.BusinessType;
import com.bedrock.framework.config.ServerConfig;
import com.bedrock.framework.security.service.TokenService;
import com.bedrock.framework.web.controller.BaseController;
import com.bedrock.framework.web.domain.AjaxResult;
import com.bedrock.framework.web.page.TableDataInfo;
import com.bedrock.project.inside.entity.ProjectInfo;
import com.bedrock.project.inside.service.IProjectInfoService;
import com.bedrock.project.inside.service.WorkHourService;
import com.bedrock.project.inside.vo.request.ProjectInfoReqVo;
import com.bedrock.project.inside.vo.response.ProjectIdAndNameResVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 项目信息Controller
 * 
 * @author bedrock
 * @date 2020-04-07
 */
@RestController
@RequestMapping("/project/manage")
public class ProjectInfoController extends BaseController
{
    @Autowired
    private IProjectInfoService projectInfoService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private ServerConfig serverConfig;

    @Autowired
    private WorkHourService workHourService;

    /**
     * 查询项目信息列表
     */
    @PreAuthorize("@ss.hasPermi('pmp:pipline:list')")
    @GetMapping("/list")
    public TableDataInfo list(ProjectInfoReqVo projectInfoReqVo)
    {
        logger.info("查询项目信息列表入参{}",projectInfoReqVo.toString());
        ProjectInfo projectInfo =
                ProjectInfo.builder().projectName(projectInfoReqVo.getProjectName()).salemanName(projectInfoReqVo.getSalemanName()).
                        projectLocation(projectInfoReqVo.getProjectLocation()).projectStatus(projectInfoReqVo.getProjectStatus()).build();
        startPage();
        List<ProjectInfo> list = projectInfoService.selectProjectInfoList(projectInfo);
        return projectInfoService.convert(getDataTable(list));
    }


    /**
     * 获取项目信息详细信息
     */
    @PreAuthorize("@ss.hasPermi('pmp:pipline:query')")
    @GetMapping(value = "/{projectId}")
    public AjaxResult getInfo(@PathVariable("projectId") Long projectId)
    {
        return AjaxResult.success(projectInfoService.selectProjectVoInfoById(projectId));
    }

    /**
     * 新增项目信息
     */
    @PreAuthorize("@ss.hasPermi('pmp:pipline:add')")
    @Log(title = "项目信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody ProjectInfoReqVo projectInfoReqVo)
    {
        if (UserConstants.NOT_UNIQUE.equals(projectInfoService.checkProjectNameUnique(projectInfoReqVo)))
        {
            return AjaxResult.error("新增项目'" + projectInfoReqVo.getProjectName() + "'失败，项目已存在");
        }
        logger.info("新增项目信息入参{}",projectInfoReqVo.toString());
        return toAjax(projectInfoService.insertProjectInfo(projectInfoReqVo));
    }

    /**
     * 修改项目信息
     */
    @PreAuthorize("@ss.hasPermi('pmp:pipline:edit')")
    @Log(title = "项目信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody ProjectInfoReqVo projectInfoReqVo)
    {
        ProjectInfo projectInfo = projectInfoService.selectProjectInfoById(projectInfoReqVo.getProjectId());
        //项目不能修改名字
        if(!projectInfo.getProjectName().equals(projectInfoReqVo.getProjectName())){
            return AjaxResult.error("修改失败，项目名称不能修改");
        }
        //仅仅修改投标状态则无需以下校验
        if(projectInfoReqVo.getProjectStatus().equals(projectInfo.getProjectStatus())){
            if(!projectInfoService.checkProjectRevisableByRole(projectInfo)){
                return AjaxResult.error("修改失败，只能有部门主管或者销售经理才能修改项目，且销售经理仅能修改自己的项目");
            }
            if(!projectInfoService.checkProjectRevisableByStatus(projectInfo)){
                return AjaxResult.error("修改失败，已关闭和已废弃的项目不能修改");
            }
            if (UserConstants.NOT_UNIQUE.equals(projectInfoService.checkProjectNameUnique(projectInfoReqVo)))
            {
                return AjaxResult.error("修改项目'" + projectInfoReqVo.getProjectName() + "'失败，项目已存在");
            }
        }
        logger.info("修改项目信息入参{}",projectInfoReqVo.toString());
        return toAjax(projectInfoService.updateProjectInfo(projectInfoReqVo));
    }

    /**
     * 删除项目信息
     */
    @PreAuthorize("@ss.hasPermi('pmp:pipline:remove')")
    @Log(title = "项目信息", businessType = BusinessType.DELETE)
	@DeleteMapping("/{projectId}")
    public AjaxResult remove(@PathVariable Long projectId)
    {
        ProjectInfo projectInfo = projectInfoService.selectProjectInfoById(projectId);
        if(!projectInfoService.checkProjectDeletableByRole(projectInfo)){
            return AjaxResult.error("删除失败，只能有部门主管或者管理员删除项目");
        }
        if(!projectInfoService.checkProjectDeletableByStatus(projectInfo)){
            return AjaxResult.error("删除项目'" + projectInfo.getProjectName() + "'失败，只能删除状态为已废弃的项目");
        }
        if(projectInfoService.checkProjectDeletableByWorkHour(projectInfo)){
            return AjaxResult.error("删除项目'" + projectInfo.getProjectName() + "'失败，该项目已关联到工时");
        }
        logger.info("删除项目信息项目id为{}",projectId);
        return toAjax(projectInfoService.deleteProjectInfoById(projectId));
    }

    /**
     * 被排除的查询项目信息列表
     */
    @GetMapping("/listbystatus")
    public TableDataInfo list(@RequestParam("excludeProjectStatus")List<String> excludeProjectStatus)
    {
        logger.info("被排除的项目状态入参{}",excludeProjectStatus.toString());
        List<ProjectIdAndNameResVo> list = projectInfoService.selectActiveProjectByDevelopers(excludeProjectStatus);
        return getDataTable(list);
    }

}
